#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   filePermissions-histsize.sh
# Version:    1.0
# Date:       2021/03/30
# Author:     laiyixin
# Email:      laiyixin@kylinos.com.cn
# History：
#             Version 1.0, 2021/03/30
# Function:   filePermissions-histsize - 历史命令保留数目限制
# Out:
#              0=> Success
#              1=> Fail
#              other=> TCONF
# ----------------------------------------------------------------------

## TODO: 使用ctrl+c退出
##
filePermissionsOnCtrlC() {
    echo "正在优雅的退出..."
    filePermissionsClean

    exit ${TFAIL}
}

## TODO: 用户界面
##
filePermissionsUSAGE() {
    cat >&1 <<EOF
--------- filePermissions-histsize - 历史命令保留数目限制 ---------
EOF
}

## TODO : 执行前的初始化
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
filePermissionsInit() {
    # 判断root用户
    if [ $(id -u) -ne 0 ]; then
        echo "Must use root ！"
        exit ${TCONF}
    fi

    # 信号捕获ctrl+c
    trap 'filePermissionsOnCtrlC' INT

    filePermissionsClean

    # 获取主要环境变量设置位置，并定义检查顺序（依据系统启动引导顺序定义）
    envList=("/etc/bashrc" "/etc/profile" "/etc/login")
    while read -r userHome; do
        for homeDir in ".bashrc" ".bash_profile" ".profile"; do
            if [ -f "${userHome}/${homeDir}" ]; then
                envList=("${userHome}/${homeDir}" "${envList[@]}")
            fi
        done
    done < <(awk -F: '{print $6}' /etc/passwd)

}

## TODO : 执行进行时的方法
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
filePermissionsTest() {
    cat >/etc/profile.d/histsize.sh <<-EOF
export HISTSIZE=${histsize}
EOF
    filePermissionsRetParse "histsize ${histsize} /etc/profile.d/histsize.sh"
    cat >/etc/profile.d/histsize.csh <<-EOF
set -r HISTSIZE=${histsize}
EOF
    filePermissionsRetParse "histsize ${histsize} /etc/profile.d/histsize.csh"

    for envFile in "${envList[@]}"; do
        if [[ -f ${envFile} ]]; then
            sed -ri "s/(^\s*)HISTSIZE=[0-9]+\s*$/\1HISTSIZE=${histsize}/g" "${envFile}"
            filePermissionsRetParse "histsize ${histsize} ${envFile}"
        fi
    done
}

## TODO : 执行收尾清除工作
##
filePermissionsClean() {
    echo "Clean ..."

}

## TODO: 解析函数返回值
## In  : $1 => log
filePermissionsRetParse() {
    local ret=$?
    local logstr=""

    if [ $# -eq 1 ]; then
        logstr="$1"
    fi

    if [ $ret -eq 0 ]; then
        echo "[pass] : ${logstr}"
    else
        echo "[fail] : ${logstr}"
        filePermissionsClean
        exit ${TFAIL}
    fi
}

## TODO : Main
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
filePermissionsMain() {
    filePermissionsUSAGE

    filePermissionsInit

    filePermissionsTest

    filePermissionsClean

    return ${TPASS}
}

filePermissionsMain
exit $?
